import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/constants.dart';

/// 音乐列表项组件
/// 用于在列表中显示音乐信息和操作按钮
class MusicTile extends StatefulWidget {
  final Music music;
  final VoidCallback? onTap;
  final VoidCallback? onPlay;
  final bool showIndex;
  final int? index;
  final bool showMoreButton;
  final bool isPlaying;
  final bool isCurrentMusic;

  const MusicTile({
    super.key,
    required this.music,
    this.onTap,
    this.onPlay,
    this.showIndex = false,
    this.index,
    this.showMoreButton = true,
    this.isPlaying = false,
    this.isCurrentMusic = false,
  });

  @override
  State<MusicTile> createState() => _MusicTileState();
}

class _MusicTileState extends State<MusicTile>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  bool _isFavorite = false;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _loadFavoriteStatus();
  }

  /// 初始化动画
  void _initAnimations() {
    _animationController = AnimationController(
      duration: AppTheme.animationDurationFast,
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  /// 加载收藏状态
  void _loadFavoriteStatus() async {
    try {
      final musicLibraryService = Provider.of<MusicLibraryService>(
        context,
        listen: false,
      );
      final isFavorite = musicLibraryService.isFavorite(widget.music.id);
      if (mounted) {
        setState(() {
          _isFavorite = isFavorite;
        });
      }
    } catch (e) {
      // 忽略错误，使用默认值
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ScaleTransition(
      scale: _scaleAnimation,
      child: GestureDetector(
        onTapDown: (_) => _animationController.forward(),
        onTapUp: (_) => _animationController.reverse(),
        onTapCancel: () => _animationController.reverse(),
        onTap: widget.onTap,
        child: Container(
          margin: const EdgeInsets.symmetric(
            horizontal: AppTheme.spacingMedium,
            vertical: AppTheme.spacingXS,
          ),
          decoration: BoxDecoration(
            color: widget.isCurrentMusic
                ? AppTheme.primaryColor.withOpacity(0.1)
                : AppTheme.surfaceDark,
            borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
            border: Border.all(
              color: widget.isCurrentMusic
                  ? AppTheme.primaryColor.withOpacity(0.5)
                  : AppTheme.primaryColor.withOpacity(0.2),
              width: widget.isCurrentMusic ? 2 : 1,
            ),
          ),
          child: Padding(
            padding: const EdgeInsets.all(AppTheme.spacingMedium),
            child: Row(
              children: [
                // 索引或播放状态指示器
                if (widget.showIndex) ...[
                  _buildIndexOrPlayingIndicator(),
                  const SizedBox(width: AppTheme.spacingMedium),
                ],

                // 封面
                _buildCover(),

                const SizedBox(width: AppTheme.spacingMedium),

                // 音乐信息
                Expanded(
                  child: _buildMusicInfo(),
                ),

                // 时长
                _buildDuration(),

                const SizedBox(width: AppTheme.spacingSmall),

                // 收藏按钮
                _buildFavoriteButton(),

                // 更多按钮
                if (widget.showMoreButton) ...[
                  const SizedBox(width: AppTheme.spacingXS),
                  _buildMoreButton(),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建索引或播放状态指示器
  Widget _buildIndexOrPlayingIndicator() {
    if (widget.isCurrentMusic && widget.isPlaying) {
      return Container(
        width: 24,
        height: 24,
        decoration: BoxDecoration(
          color: AppTheme.primaryColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: const Icon(
          Icons.equalizer,
          color: Colors.white,
          size: 16,
        ),
      );
    }

    if (widget.index != null) {
      return Container(
        width: 24,
        height: 24,
        decoration: BoxDecoration(
          color: AppTheme.primaryColor.withOpacity(0.2),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Center(
          child: Text(
            '${widget.index! + 1}',
            style: const TextStyle(
              fontSize: AppTheme.fontSizeXS,
              fontWeight: FontWeight.w600,
              color: AppTheme.primaryColor,
            ),
          ),
        ),
      );
    }

    return const SizedBox(width: 24, height: 24);
  }

  /// 构建封面
  Widget _buildCover() {
    return Container(
      width: 50,
      height: 50,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        gradient: AppTheme.primaryGradient,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        child: widget.music.coverArt != null
            ? Image.asset(
                widget.music.coverArt!,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return _buildDefaultCover();
                },
              )
            : _buildDefaultCover(),
      ),
    );
  }

  /// 构建默认封面
  Widget _buildDefaultCover() {
    return const Icon(
      Icons.music_note,
      color: Colors.white,
      size: AppTheme.iconSizeMedium,
    );
  }

  /// 构建音乐信息
  Widget _buildMusicInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          widget.music.title,
          style: TextStyle(
            fontSize: AppTheme.fontSizeMedium,
            fontWeight: FontWeight.w600,
            color: widget.isCurrentMusic
                ? AppTheme.primaryColor
                : AppTheme.textPrimaryDark,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 2),
        Text(
          widget.music.artist,
          style: const TextStyle(
            fontSize: AppTheme.fontSizeSmall,
            color: AppTheme.textSecondaryDark,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        if (widget.music.album?.isNotEmpty == true) ...[
          const SizedBox(height: 1),
          Text(
            widget.music.album!,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeXS,
              color: AppTheme.textHintDark,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ],
    );
  }

  /// 构建时长
  Widget _buildDuration() {
    return Text(
      widget.music.formattedDuration,
      style: const TextStyle(
        fontSize: AppTheme.fontSizeSmall,
        color: AppTheme.textHintDark,
        fontFeatures: [FontFeature.tabularFigures()],
      ),
    );
  }

  /// 构建收藏按钮
  Widget _buildFavoriteButton() {
    return GestureDetector(
      onTap: _toggleFavorite,
      child: Container(
        width: 32,
        height: 32,
        decoration: BoxDecoration(
          color: _isFavorite
              ? AppTheme.errorColor.withOpacity(0.2)
              : Colors.transparent,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Icon(
          _isFavorite ? Icons.favorite : Icons.favorite_border,
          color: _isFavorite ? AppTheme.errorColor : AppTheme.textHintDark,
          size: AppTheme.iconSizeSmall,
        ),
      ),
    );
  }

  /// 构建更多按钮
  Widget _buildMoreButton() {
    return GestureDetector(
      onTap: _showMoreOptions,
      child: Container(
        width: 32,
        height: 32,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(16),
        ),
        child: const Icon(
          Icons.more_vert,
          color: AppTheme.textHintDark,
          size: AppTheme.iconSizeSmall,
        ),
      ),
    );
  }

  /// 切换收藏状态
  void _toggleFavorite() async {
    try {
      final musicLibraryService = Provider.of<MusicLibraryService>(
        context,
        listen: false,
      );

      if (_isFavorite) {
        await musicLibraryService.removeFavorite(widget.music.id);
      } else {
        await musicLibraryService.addFavorite(widget.music.id);
      }

      setState(() {
        _isFavorite = !_isFavorite;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              _isFavorite ? '已添加到收藏' : '已从收藏中移除',
            ),
            backgroundColor:
                _isFavorite ? AppTheme.successColor : AppTheme.warningColor,
            duration: const Duration(seconds: 1),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('操作失败: $e'),
            backgroundColor: AppTheme.errorColor,
          ),
        );
      }
    }
  }

  /// 显示更多选项
  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.surfaceDark,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(AppTheme.radiusLarge),
        ),
      ),
      builder: (context) => _buildMoreOptionsSheet(),
    );
  }

  /// 构建更多选项面板
  Widget _buildMoreOptionsSheet() {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingLarge),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题
          Row(
            children: [
              _buildCover(),
              const SizedBox(width: AppTheme.spacingMedium),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.music.title,
                      style: const TextStyle(
                        fontSize: AppTheme.fontSizeMedium,
                        fontWeight: FontWeight.w600,
                        color: AppTheme.textPrimaryDark,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Text(
                      widget.music.artist,
                      style: const TextStyle(
                        fontSize: AppTheme.fontSizeSmall,
                        color: AppTheme.textSecondaryDark,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ],
          ),

          const SizedBox(height: AppTheme.spacingLarge),

          // 选项列表
          _buildOptionItem(
            Icons.play_arrow,
            '播放',
            () {
              Navigator.pop(context);
              widget.onPlay?.call();
            },
          ),
          _buildOptionItem(
            Icons.playlist_add,
            '添加到播放列表',
            () {
              Navigator.pop(context);
              _addToPlaylist();
            },
          ),
          _buildOptionItem(
            _isFavorite ? Icons.favorite : Icons.favorite_border,
            _isFavorite ? '从收藏中移除' : '添加到收藏',
            () {
              Navigator.pop(context);
              _toggleFavorite();
            },
          ),
          _buildOptionItem(
            Icons.info_outline,
            '音乐信息',
            () {
              Navigator.pop(context);
              _showMusicInfo();
            },
          ),

          const SizedBox(height: AppTheme.spacingMedium),
        ],
      ),
    );
  }

  /// 构建选项项
  Widget _buildOptionItem(
    IconData icon,
    String title,
    VoidCallback onTap,
  ) {
    return ListTile(
      leading: Icon(
        icon,
        color: AppTheme.primaryColor,
        size: AppTheme.iconSizeMedium,
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontSize: AppTheme.fontSizeMedium,
          color: AppTheme.textPrimaryDark,
        ),
      ),
      onTap: onTap,
      contentPadding: EdgeInsets.zero,
    );
  }

  /// 添加到播放列表
  void _addToPlaylist() {
    final audioService =
        Provider.of<AudioPlayerService>(context, listen: false);
    audioService.addToQueue(widget.music);

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('已添加到播放列表'),
        backgroundColor: AppTheme.successColor,
        duration: Duration(seconds: 1),
      ),
    );
  }

  /// 显示音乐信息
  void _showMusicInfo() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.surfaceDark,
        title: const Text(
          '音乐信息',
          style: TextStyle(
            color: AppTheme.textPrimaryDark,
            fontWeight: FontWeight.bold,
          ),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInfoRow('标题', widget.music.title),
            _buildInfoRow('艺术家', widget.music.artist),
            _buildInfoRow('专辑', widget.music.album ?? '未知专辑'),
            _buildInfoRow('时长', widget.music.formattedDuration),
            _buildInfoRow('文件大小', widget.music.formattedFileSize),
            if (widget.music.year != null && widget.music.year! > 0)
              _buildInfoRow('年份', widget.music.year.toString()),
            if (widget.music.genre?.isNotEmpty == true)
              _buildInfoRow('流派', widget.music.genre!),
            _buildInfoRow('文件路径', widget.music.filePath),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text(
              '关闭',
              style: TextStyle(color: AppTheme.primaryColor),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textSecondaryDark,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textPrimaryDark,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
